from .base_webdriver import BaseWebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time


class ServiceRuleUI(BaseWebDriver):

    def __init__(self):
        super().__init__()

    def add_svc_rule(self, ruleName: str, ruleType: str,
                     minFee: str, estFee: str, feeRate=None, desc: str = None):
        """
        添加业务规则
            ruleName (str): 规则名称
            ruleType (str): 规则类型，只能是：后付费-上报业务量、预付费-下发费用、预付费-下发业务量
            minFee (str): 最小费用，不需要时，填写空字符串
            estFee (str): 预计费用，不需要时，填写空字符串
            feeRate: 费率， 如果ruleType是
               预付费-下发费用： 不用填写
               预付费-下发业务量： 格式为 ['千瓦时', '1']， 元素分别是 单位、单价
               后付费-上报业务量： 格式为 [
                    ['10L', '小时','1'],
                    ['20L', '小时','2'],
                ]， 每个元素里面分别是 ： 业务码、单位、单价
            desc (str): 描述
        """
        # 填写规则名称
        ele = self.wd.find_element(By.CSS_SELECTOR, '.add-one-form > .field:nth-child(1) >input')
        ele.clear()
        # 处理None值的情况
        if ruleName is not None:
            ele.send_keys(ruleName)

        # 选择规则类型（等待下拉框可点击）
        select_el = self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".add-one-form select")))
        select = Select(select_el)
        select.select_by_visible_text(ruleType)
        # 依赖后续字段的定位作为页面稳定标志，无需固定 sleep

        # 根据规则类型填写费用信息
        if ruleType != '后付费-上报业务量':
            # 填写最小费用
            ele = self.wd.find_element(By.CSS_SELECTOR, '.add-one-form > .field:nth-child(3) >input')
            ele.clear()
            if minFee:
                ele.send_keys(minFee)

            # 填写预计费用
            ele = self.wd.find_element(By.CSS_SELECTOR, '.add-one-form > .field:nth-child(4) >input')
            ele.clear()
            if estFee:
                ele.send_keys(estFee)

        # 填写描述, 用xpath而不用 .field:nth-child 因为后付费-上报业务量 次序会变
        if desc:
            ele = self.wd.find_element(By.XPATH,
                                       "//*[@class='add-one-submit-btn-div']/preceding-sibling::*[1]/input")
            ele.clear()
            ele.send_keys(desc)

        # 费率填写
        if ruleType == '预付费-下发费用':
            # 没有费率设置
            pass

        elif ruleType == '后付费-上报业务量':
            # 先删除上次添加遗留的费率（短显式等待驱动循环，避免隐式切换）
            while True:
                try:
                    btn = self.wait_short.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.fee-rate span:last-child')))
                    btn.click()
                    # 等待该条目消失以避免点击过快导致 DOM 未刷新
                    time.sleep(0.2)
                except TimeoutException:
                    break

            # 添加新的费率条目
            for one in feeRate:
                self.wd.find_element(By.CSS_SELECTOR, '.fee-rate-list button').click()

                entry = self.wd.find_element(By.CSS_SELECTOR, 'div.fee-rate:nth-last-child(2)')

                # 业务码
                entry.find_element(By.CSS_SELECTOR, 'input:nth-of-type(1)').send_keys(one[0])
                # 计费单位
                entry.find_element(By.CSS_SELECTOR, 'input:nth-of-type(2)').send_keys(one[1])
                # 单位价格
                entry.find_element(By.CSS_SELECTOR, 'input:nth-of-type(3)').send_keys(one[2])

        elif ruleType == '预付费-下发业务量':
            entry = self.wd.find_element(By.CSS_SELECTOR, 'div.fee-rate')

            # 计费单位 - 先清空再输入
            unit_input = entry.find_element(By.CSS_SELECTOR, 'input:nth-of-type(1)')
            unit_input.clear()
            unit_input.send_keys(feeRate[0])
            
            # 单位价格 - 先清空再输入
            price_input = entry.find_element(By.CSS_SELECTOR, 'input:nth-of-type(2)')
            price_input.clear()
            price_input.send_keys(feeRate[1])
        else:
            raise Exception('ruleType 参数值错误')

        # 确定提交（等待按钮可点击）
        submit_btn = self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.add-one-submit-btn-div .btn')))
        submit_btn.click()

    def get_first_page_svc_rules(self):
        """
        获取第一页的业务规则列表
            list: 包含业务规则信息的列表
        """
        # 确保快照元素已出现（短显式等待避免隐式切换）
        try:
            self.wait_short.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.result-list-item-info')))
        except TimeoutException:
            pass
        items = self.wd.find_elements(By.CSS_SELECTOR, '.result-list-item-info')

        rules = []
        for item in items:
            nameValueList = item.find_elements(By.CSS_SELECTOR, '.field>.field-name, .field>.field-value')
            itemInfo = []
            for idx, _ in enumerate(nameValueList):
                if (idx + 1) % 2 == 0:
                    nameEle, valueEle = nameValueList[idx - 1], nameValueList[idx]
                    if nameEle.text == '规则内容':
                        ruleContent = {}
                        sfns = valueEle.find_elements(By.CSS_SELECTOR, '.sub-field-name')
                        for sfnEle in sfns:
                            sfn = sfnEle.text
                            sfvEle = sfnEle.find_element(By.XPATH, "following-sibling::*[1]")
                            if sfn == '费率':
                                ruleContent[sfn] = sfvEle.text
                            else:
                                ruleContent[sfn] = sfvEle.text

                        itemInfo.append(ruleContent)
                    else:
                        itemInfo.append(valueEle.text)

            rules.append(itemInfo)

        return rules